﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DmxInterface;

namespace DmxLightShow {
	public partial class Form1 : Form {
		public Form1() {
			InitializeComponent();
		}

		Factory _factory;
		Device _device;

		Universe _universe = new Universe();

		private void init(object sender, EventArgs e) {
			try {
				_factory = new Factory();
			}
			catch (Exception ex) {
				MessageBox.Show("Error: " + ex.Message);
				return;
			}

			lblVersion.Text = _factory.Version.ToString();
		}

		private void open(object sender, EventArgs e) {
			if (_factory == null)
				return;

			try {
				_device = _factory.CreateDevice();
				_device.Open();

				_factory.Engine.Register(_device, _universe);
				_factory.Engine.Start();
			}
			catch (Exception ex) {
				MessageBox.Show("Error: " + ex.Message);
				return;
			}

			MessageBox.Show("Device status: " + _device.IsOpen);
		}

		private void close(object sender, EventArgs e) {
			if (_device == null)
				return;

			try {
				_factory.Engine.TryDeregister(_device);
				_factory.Engine.Stop();

				_device.Dispose();
				_device = null;
			}
			catch (Exception ex) {
				MessageBox.Show("Error: " + ex.Message);
				return;
			}

			MessageBox.Show("Device closed.");
		}

		private void shutdown(object sender, EventArgs e) {
			close(sender, e);

			if (_factory == null)
				return;

			try {
				_factory.Dispose();
			}
			catch (Exception ex) {
				MessageBox.Show("Error: " + ex.Message);
				return;
			}

			MessageBox.Show("Library unloaded.");
		}

		protected override void OnClosing(CancelEventArgs e) {
			base.OnClosing(e);

			shutdown(null, EventArgs.Empty);
		}

		private void SliderChange(object sender, EventArgs e) {
			var val = (byte)trackBar1.Value;
			
			_universe[0] = val;
		}
	}
}
